package com.dm.cloud.images.schedule;

import cn.hutool.core.io.FileUtil;
import com.dm.cloud.images.util.LocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 定时清理工作目录
 */
@Component
@Slf4j
public class LocalTask {

    @Value("${dm.images.local.public-clean-max-time:24*60*60*1000}")
    private String cleanTime;

    private SimpleDateFormat dateDirFormat=new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private LocalUtil localUtil;

    /**
     * 每500秒执行一次工作目录清理任务
     */
    @Scheduled(fixedDelay = 500000)
    public void cleanWork()  {
        File cacheFile = localUtil.getWorkFile("cache");
        log.info("定时清理目录："+cacheFile.getAbsolutePath());
        try {
            Long cleanMaxTime = fixTime(cleanTime);
            Date tDate=new Date();
            if(cacheFile.exists() && cacheFile.isDirectory()){
                File[] childs = cacheFile.listFiles();
                if(null!=childs && childs.length>0){
                    for(File dateDir:childs){
                        try{
                            Date dirDate=dateDirFormat.parse(dateDir.getName());
                            if(tDate.getTime()-dirDate.getTime()>cleanMaxTime){
                                FileUtil.del(dateDir);
                            }
                        }catch (Exception e){
                            //不符合规则的目录直接滤过
                        }
                    }
                }
            }
        }catch (Exception e){
            //未删除不做记录
        }
    }

    private Long fixTime(String cleanTime) {
        List<String> list = Arrays.asList(cleanTime.split("\\*"));
        Long time = 1L;
        for (String item : list) {
            time *= Long.valueOf(item);
        }
        return time;
    }
}
